package com.jt.config;

import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义的全局过滤器,作用域所有路由
 */
//@Component
public class AuthGatewayFilter implements GlobalFilter, Ordered {

        @Value("${white.prefix}")
        private String whitePrefix;
    /**你的业务可以写到这个filter方法内部
     * @param exchange 基于此对象可以获取请求和响应对象
     * @param chain 这个对象指向了一个过滤链(这个链中有多个过滤器)
     * */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange,
                             GatewayFilterChain chain) {
        //1.获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //2.获取请求数据
        String path = request.getURI().getPath();
        System.out.println("path="+path);
        //String username=request.getQueryParams().getFirst("username");
        //3.对请求数据进行处理
        //例如判定请求的path是否在我们允许的范围之内
        System.out.println("whitePrefix="+whitePrefix);
        //判断路径的前缀
        if(path.startsWith(whitePrefix)){
            //4.返回响应结果
            return chain.filter(exchange);//将请求交给下一个过滤器进行处理
        }

            //获取响应对象
            ServerHttpResponse response = exchange.getResponse();
            //设置响应状态码,这里的值为502
            //response.setStatusCode(HttpStatus.BAD_GATEWAY);
            //结束当前请求
            //return response.setComplete();//直接结束
            //假如希望响应一些具体内容到客户端
            //String content="request failure";
            //byte[] bytes=content.getBytes();
            Map<String,Object> map=new HashMap<>();
            map.put("message","request failure");
            map.put("status",502);
            //将map对象转换为json字符串?
            //String jsonStr="{\"message\":\"request failure\",\"status\":502}";
            Gson gson=new Gson();
             String jsonStr=gson.toJson(map);//将map对象转换json格式字符串.
            byte[] bytes=jsonStr.getBytes();
            DataBuffer dataBuffer=
                    response.bufferFactory().wrap(bytes);
            return response.writeWith(Mono.just(dataBuffer));
            //Spring WebFlux,Mono是一个可以封装0个或1个元素的序列对象.
    }
    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
